from typing import List
from fastapi import APIRouter, Depends, HTTPException

from basic import BaseSchema, logger
from service import EntryService, IEntryService

router = APIRouter(prefix="/entry", tags=["entry"])

class EntryCreateRequest(BaseSchema):
    repo_key: str
    entry_path: str
    is_dir: bool

class EntryCreateResponse(BaseSchema):
    entry_key: str

@router.post("/create")
async def create_entry(
    params: EntryCreateRequest,
    service: IEntryService = Depends(EntryService),
):
    try:
        return await service.create_entry(params.repo_key, params.entry_path, params.is_dir)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


class EntryDeleteRequest(BaseSchema):
    repo_key: str
    entry_key: str

class EntryDeleteResponse(BaseSchema):
    entry_key: str
    
@router.post("/delete")
async def delete_entry(
    params: EntryDeleteRequest,
    service: IEntryService = Depends(EntryService)
):
    try:
        return await service.delete_entry(params.entry_key)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

class EntryUpdateRequest(BaseSchema):
    repo_key: str
    entry_key: str
    update_key: str
    update_value: str

class EntryUpdateResponse(BaseSchema):
    entry_key: str

@router.post("/update", response_model=EntryUpdateResponse)
async def update_entry(
    params: EntryUpdateRequest,
    service: IEntryService = Depends(EntryService),
):
    try:
        return await service.update_entry(
            params.repo_key,
            params.entry_key, 
            params.update_key, 
            params.update_value, 
        )
    except Exception as e:
        logger.error(f"Error updating entry: {e}")
        raise HTTPException(status_code=400, detail=str(e))


########################################
class EntryListRequest(BaseSchema):
    repo_key: str
    entry_key: str
    
class _EntryChildrenResponseItem(BaseSchema):
    path: str
    entry_key: str
    is_dir: bool
    file_key: str | None
        
EntryListResponse = List[_EntryChildrenResponseItem]

@router.post("/list", response_model=EntryListResponse)
async def get_entry_children(
    params: EntryListRequest,
    service: IEntryService = Depends(EntryService),
):
    try:
        return await service.get_entry_children(params.entry_key)
    except Exception as e:
        logger.error(f"Error getting entry children: {e}")
        raise HTTPException(status_code=400, detail=str(e))


